const { miniProgram: { envVersion } } = wx.getAccountInfoSync()

const baseUrl = {
  // 开发版
  develop: "https://youliaotest.jaid.cn",
  // 体验版
  trial: "https://materialdesign.henyouliao.cn",
  // 正式版
  release: "https://materialdesign.henyouliao.cn"
}[envVersion || 'release']

// 设置请求拦截器
const fetch = (params = {}) => {
  const CNPASS = wx.getStorageSync('CNPASS')
  if (params.method === 'POST') {
    if (params.data && params.data.content) {
      params.header = { 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8', cookie: 'CNPASS=' + CNPASS }
      params.data.content = encodeURIComponent(JSON.stringify(params.data.content))
    } else {
      if (!params.data) params.data = {}
      params.header = { 'Content-Type': 'application/json;charset=utf-8', cookie: 'CNPASS=' + CNPASS }
    }
    // params.header = { 'Content-Type': 'application/json;charset=utf-8' }
  } else {
    params.header = { 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8' }
    params.timestamp = +new Date()
  }
  params.url = baseUrl + params.url

  // 返回promise
  return wx.$pro.request({ ...params })
    .then(async ({ data }) => {
      // ... 各种异常情况的逻辑处理
      if (data.ResultSet && data.ResultSet.status === 0) return Promise.resolve(data)
      else {
        if (data.ResultSet && data.ResultSet.status === 20000) {
          wx.$nav.redirectTo('/pages/login/index')
        }
        return Promise.reject(data)
      }
    })
}
export { fetch }